const {
    str_status,
    pro,
    timeStr,
    http
} = require('../common/pro_mysql');
const {
    verifyToken
} = require('../common/jwt_token');
const svgCaptcha = require('svg-captcha');
// 引入multer
const multer = require('multer');
// 文件上传
async function UpLoad(req,res){
    console.log(req.file);
    res.send(str_status(1,'上传成功',`http://192.168.17.126/static/${req.file.filename}`))
}

// 获取验证码接口
async function GetCode(req,res){
    const captcha = svgCaptcha.create({
        inverse: false, // 翻转颜色
        fontSize: 48, // 字体大小
        noise: 2, // 干扰线条数
        width: req.body.width || 150, // 宽度
        height: req.body.height || 50, // 高度
        size: 4, // 验证码长度
        ignoreChars: '0o1i', // 验证码字符中排除 0o1i
        color: true, // 验证码是否有彩色
        background: '#cc9966', // 验证码图片背景颜色
    })
    //保存到cookie,忽略大小写
    res.type('svg')
    res.send(captcha)
}
// 上传文件
var up = multer({
    storage: multer.diskStorage({
        destination: function (req,file,cb){
            cb(null,'static/')
        },
        filename: function (req,file,cb){
            let arr = file.originalname.split('.');
            cb(null,Date.now()+'.'+arr[arr.length-1])
        }
    })
})

// 获取手机验证码接口
async function SendCode(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let {msg} =await verifyToken(token);
        let {loginPhone,ID} = msg;
        let tSql = `select * from polarTaskList where task_type=2 and task_id in (select ID from polarTaskTime where createTime=${timeStr().s_time} and endTime=${timeStr().e_time})`;
        let {result} = await pro(tSql);
        let userArr = JSON.parse(result[0].user_id);
        if(userArr.indexOf(ID) == -1){
            let sSql = `select * from provingCode where user_id=${ID} and user_phone="${loginPhone}" and createTime>${Date.now()-10*60*1000}`;
            let {result} = await pro(sSql);
            if(result.length >= 2){
                res.send(str_status(0,'发送频繁，请稍后再试'))
            }else{
                let ranMath = Math.floor((Math.random()*899999)+100000); 
                let data = await http(`https://53cba1e3-c107-4211-b470-8de9edc77079.bspapp.com/sendCode?loginPhone=${loginPhone}&code=${ranMath}&minute=30`)
                if(data.success){
                    let sql = `insert into provingCode (user_id,user_phone,code,createTime) values (${ID},${loginPhone},${ranMath},${Date.now()})`
                    let {result} = await pro(sql)
                    res.send(str_status(1,'验证码发送成功，请注意查看',{
                        code: result.insertId
                    }))
                }else{
                    res.send(str_status(0,'发送失败，请联系客服'))
                }
            }      
        }else{
            res.send(str_status(0,'本轮已经完成过此任务了，下轮再来吧!'))
        }
    }
}

module.exports = {
    GetCode,
    UpLoad,
    up,
    SendCode
}